﻿#include "log.h"
#include <QDate>
#include <QMessageBox>
#include <QDebug>
#include <QFile>
#include <QTextStream>
#include <QDir>
Log* Log::instance = new Log();
Log::Log()
{
    applicationPath = QDir::currentPath();
}

void Log::Debug(const QString &value)
{
    if(instance == nullptr)
        instance = new Log();
    instance->WriteLog(0,value);
}

void Log::Error(const QString &value)
{
    if(instance == nullptr)
        instance = new Log();
    instance->WriteLog(2,value);
#ifdef QT_NO_DEBUG
    QMessageBox::critical(nullptr,u8"错误",value);
#endif
}

void Log::Warning(const QString &value)
{
    instance->WriteLog(1,value);
}

Log::~Log()
{
    if(file!=nullptr){
        file->close();
    }
}

void Log::WriteLog(int type, const QString &value)
{
#ifdef QT_NO_DEBUG
    if(textStream == nullptr){
        file = new QFile(QString("%1/log").arg(applicationPath));
        if(!file->open(QIODevice::WriteOnly|QIODevice::Append|QIODevice::Text)){
            QMessageBox::critical(nullptr,u8"错误",u8"无法打开日志");
            return;
        }
        textStream = new QTextStream(file);
    }

    *textStream << QString("[%1][%2] %3\n").arg(QDate::currentDate().toString("yyyy-MM-dd")).arg(getType(type)).arg(value);
    textStream->flush();
#else
    qDebug()<< QString("[%1][%2] %3").arg(QDate::currentDate().toString("yyyy-MM-dd")).arg(getType(type)).arg(value);
#endif

}

QString Log::getType(int type)
{
    switch(type){
    case 1:return "Warning";
    case 2:return "Error";
    default:
        return "Debug";
    }
}
